package com.lcf.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.framework.utils.UserUtils;
import com.lcf.system.dao.MoviePrizeDao;
import com.lcf.system.entity.Movie;
import com.lcf.system.entity.MoviePrize;
import com.lcf.system.service.MoviePrizeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 点赞(MoviePrize)表服务实现类
 *
 * @author lcf
 * @since 2025-05-07 22:23:23
 */
@Service("moviePrizeService")
public class MoviePrizeServiceImpl extends ServiceImpl<MoviePrizeDao, MoviePrize> implements MoviePrizeService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(long movieId) {
        Db.lambdaQuery(MoviePrize.class)
                .eq(MoviePrize::getMovieId, movieId)
                .eq(MoviePrize::getUserId, UserUtils.getUserId())
                .oneOpt()
                .ifPresentOrElse(
                        x -> {
                            if (x.getIsPrize() == 0) {
                                Db.lambdaQuery(Movie.class)
                                        .eq(Movie::getId, movieId)
                                        .oneOpt()
                                        .ifPresent(m -> {
                                            m.setPrizeTimes(m.getPrizeTimes() + 1);
                                            m.updateById();
                                        });
                            }

                            x.setIsPrize(1);
                            x.updateById();
                        },
                        () -> {
                            new MoviePrize(UserUtils.getUserId(), movieId).insert();
                            Db.lambdaQuery(Movie.class)
                                    .eq(Movie::getId, movieId)
                                    .oneOpt()
                                    .ifPresent(m -> {
                                        m.setPrizeTimes(m.getPrizeTimes() + 1);
                                        m.updateById();
                                    });
                        }
                );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancel(long movieId) {
        Db.lambdaQuery(MoviePrize.class)
                .eq(MoviePrize::getMovieId, movieId)
                .eq(MoviePrize::getUserId, UserUtils.getUserId())
                .oneOpt()
                .ifPresent(x -> {
                    x.setIsPrize(0);
                    x.updateById();

                    Db.lambdaQuery(Movie.class).eq(Movie::getId, movieId).oneOpt().ifPresent(y -> {
                        y.setPrizeTimes(Math.max(y.getPrizeTimes() - 1, 0));
                        y.updateById();
                    });
                });
    }
}

